package com.briup.estore.controller;

import com.briup.estore.entity.ShopEntity;
import com.briup.estore.entity.UserEntity;
import com.briup.estore.service.RecommendShopService;
import com.briup.estore.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author adam
 * @date 2023/3/31
 */
@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RecommendShopService recommendShopService;

    @PostMapping("register")
    public String register(UserEntity user, Model model) {
        try {
            userService.register(user);
            return "login";
        } catch (Exception e) {
            model.addAttribute("msg", e.getMessage());
            return "register";
        }

    }


    @PostMapping("login")
    public String login(String loginName, String password, HttpSession session, Model model) {
        try {
            UserEntity user = userService.login(loginName, password);
            List<ShopEntity> recommendShops =recommendShopService.recommendShopsByUser(user.getId());
            session.setAttribute("recommendShops",recommendShops);
            session.setAttribute("user",user);
            return "index";
        } catch (RuntimeException e) {
            model.addAttribute("msg",e.getMessage());
            return "login";
        }
    }

    @GetMapping("exit")
    public String exit(HttpSession session){
        session.removeAttribute("user");
        return "login";
    }
}
